package org.changs.nav.ui.nav;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.amap.api.services.core.PoiItem;

import org.changs.aplug.interf.OnBackPressedListener;
import org.changs.aplug.widget.irecyclerview.SimpleAdapter;
import org.changs.nav.R;
import org.changs.nav.databinding.MainPoiListFragmentBinding;
import org.changs.nav.databinding.SearchResultItemBinding;
import org.changs.nav.delegate.MapSwitchDelegate;
import org.changs.nav.delegate.amap.domain.PoiPoint;
import org.changs.nav.delegate.global.AmapNavHelper;
import org.changs.nav.event.PoiItemClickEvent;
import org.changs.nav.mvp.PoiListContract;
import org.changs.nav.mvp.PoiListPresenter;
import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

import javax.inject.Inject;

import aplug.data.db.CollectInfoHelper;
import aplug.data.db.mode.CollectInfo;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by yincs on 2017/10/14.
 */

public class PoiListFragment extends BaseMapFragment implements OnBackPressedListener, PoiListContract.V {

    private static final String TAG_POI_ITEMS = "TAG_POI_ITEMS";
    private static final String TAG_SELECT_POSITION = "TAG_SELECT_POSITION";
    private static final String TAG_SET_COLLECT = "TAG_SET_COLLECT";


    public static PoiListFragment newInstance(ArrayList<PoiItem> poiItems) {
        return newInstance(poiItems, -1);
    }

    /**
     * 设置收藏
     *
     * @param collectId 收藏Id
     */
    public static PoiListFragment newInstance(ArrayList<PoiItem> poiItems, int collectId) {
        Bundle args = new Bundle();
        args.putParcelableArrayList(TAG_POI_ITEMS, poiItems);
        args.putInt(TAG_SET_COLLECT, collectId);
        PoiListFragment fragment = new PoiListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private MainPoiListFragmentBinding mBinding;
    private PoiListAdapter mPoiListAdapter = new PoiListAdapter();
    private int mCollectId;
    private String mCollectName;
    @Inject PoiListPresenter mPoiListPresenter;
    @Inject MapSwitchDelegate mMapSwitchDelegate;
    @Inject AmapNavHelper mAmapNavHelper;
    @Inject CollectInfoHelper mCollectInfoHelper;

    @Override
    public View setup(LayoutInflater inflater, @Nullable ViewGroup container,
                      @Nullable Bundle savedInstanceState) {

        mBinding = DataBindingUtil.inflate(inflater, R.layout.main_poi_list_fragment, container, false);
        mBinding.btnGoHere.setOnClickListener(v -> {
            PoiItem selectItem = mPoiListAdapter.getSelectItem();
            if (mCollectId != -1) {
                mCollectInfoHelper.insertOrReplace(new CollectInfo((long) mCollectId, CollectInfoHelper.getDefaultCollectName(mCollectId),
                        selectItem.getSnippet(), selectItem.getLatLonPoint().getLatitude(), selectItem.getLatLonPoint().getLongitude()))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(id -> getContext().onBackPressed());
            } else {
                mPoiListPresenter.clickGoHere(selectItem);
            }
        });

        mBinding.rccSearchResult.setLayoutManager(new LinearLayoutManager(getContext()));
        mBinding.rccSearchResult.setIAdapter(mPoiListAdapter);

        ArrayList<PoiItem> poiItems;
        int select = 0;
        if (savedInstanceState == null) {
            poiItems = getArguments().getParcelableArrayList(TAG_POI_ITEMS);
        } else {
            poiItems = savedInstanceState.getParcelableArrayList(TAG_POI_ITEMS);
            select = savedInstanceState.getInt(TAG_SELECT_POSITION, 0);
        }
        mCollectId = getArguments().getInt(TAG_SET_COLLECT, -1);
        if (mCollectId != -1) {
            mBinding.btnGoHere.setText(String.format("设置成%s", CollectInfoHelper.getDefaultCollectName(mCollectId)));
        }
        showPostList(poiItems, select);
        return mBinding.getRoot();
    }

    //细节优化
    //地图下载的那个是周四给的。要2.5天
    @Override
    public void onResume() {
        super.onResume();
        mPoiListPresenter.attachView(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        mPoiListPresenter.detachView();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelableArrayList(TAG_POI_ITEMS, (ArrayList<PoiItem>) mPoiListAdapter.getData());
        outState.putInt(TAG_SELECT_POSITION, mPoiListAdapter.getSelectPosition());
    }

    @Override
    public boolean onBackPressed() {
        return false;
    }

    @Override
    public void showPostList(ArrayList<PoiItem> poiItems, int select) {
        mPoiListAdapter.setSelectIndex(select);
        mPoiListAdapter.getData().clear();
        mPoiListAdapter.getData().addAll(poiItems);
        mPoiListAdapter.notifyDataSetChanged();
        hideLoading();

        PoiPoint endPoint = mAmapNavHelper.getEndPoint();
        if (endPoint != null) mBinding.tvSearch.setText(endPoint.getName());
    }

    @Override
    public void startRouteView(int[] ints) {
        PoiItem item = mPoiListAdapter.getSelectItem();
        PoiPoint endPoint = new PoiPoint(item.getCityName(), item.getSnippet(),
                item.getLatLonPoint().getLatitude(), item.getLatLonPoint().getLongitude());

        mMapSwitchDelegate.switch2RouteList(ints, endPoint);
        startFragment(this, RouteListFragment.newInstance(ints));
    }

    private class PoiListAdapter extends SimpleAdapter<PoiItem, SearchResultItemBinding> {
        public PoiListAdapter() {
            super(R.layout.search_result_item);
        }

        @Override
        public void onBindViewHolder(final SearchResultItemBinding binding, int position) {
            final PoiItem poiItem = getData().get(position);
            final String name = poiItem.toString();
            binding.tvName.setText(String.format("%d.%s", position + 1, name));
            binding.tvAddress.setText(String.format("%s-%s-%s-%s", poiItem.getProvinceName(),
                    poiItem.getCityName(), poiItem.getAdName(), poiItem.getSnippet()));
            final boolean select = isSelect(position);
            binding.btnMore.setVisibility(select ? View.VISIBLE : View.GONE);
            final int index = position;
            binding.getRoot().setOnClickListener(v -> {
                if (isSelect(index)) {
//                    mPoiPresenter.clickPoiItem(poiItem);
                } else {
                    EventBus.getDefault().post(new PoiItemClickEvent(index));
                    setSelectIndex(index);
                    notifyDataSetChanged();
                }
            });
        }
    }

    @Override
    protected boolean getOutsideTouchable() {
        return false;
    }
}
